from django.db.models import Model
from rest_framework.serializers import ModelSerializer
from django.core.paginator import Paginator
from django.db.models import Q

from src.utils.record.BaseRecord import BaseRecord
from common.models import TbBasicTable
from common.serializer import BasicTableSerializers


class TbRecord(BaseRecord):
    model: Model = TbBasicTable
    serializer: ModelSerializer = BasicTableSerializers

    def create_record(self, **kwargs):
        review_info = self.create_base_info()
        for k, v in kwargs.items():
            review_info[k] = v
        record_ser = self.serializer(data=review_info)
        if record_ser.is_valid():
            return record_ser.save()
        else:
            raise ValueError(str(record_ser.errors))

    def uniqueness_create(self, *args, **kwargs):
        """
        唯一添加
        """
        uni_info = kwargs.get("uni_info")  # 唯一性的条件
        add_info = kwargs.get("add_info")  # 添加条件
        exits_message = kwargs.get("exits_message")  # 存在时错误提示的文案
        if self.exits_record(**uni_info, is_delete=0):
            if exits_message is None:
                exits_message = "改记录已存在"
            raise ValueError(exits_message)
        else:
            return self.create_record(**add_info)

    def get_random_record(self, **kwargs):
        """
        随机获取一条记录
        """
        return self.filter_record_obj(**kwargs).order_by("?").first()

    def get_record(self, record_id):
        """
        查询某条记录
        """
        try:
            record = self.model.objects.get(uid=record_id)
        except self.model.DoesNotExist:
            raise ValueError("记录不存在")
        return record

    def exits_record(self, **kwargs):
        """
        相应记录是否存在
        """
        records = self.model.objects.filter(**kwargs)
        if records.count() > 0:
            return True
        else:
            return False

    def get_record_condition(self, **kwargs):
        """
        条件查询单条数据
        """
        try:
            record = self.model.objects.get(**kwargs)
        except self.model.DoesNotExist:
            raise ValueError("记录不存在")
        return record

    def get_record_detail(self, record_id):
        try:
            record = self.model.objects.get(uid=record_id, is_delete=0)
        except self.model.DoesNotExist:
            raise ValueError("记录不存在")
        record_ser = self.serializer(instance=record)
        return record_ser.data

    def edit_record(self, record_id, **kwargs):
        kwargs["uid"] = record_id
        try:
            record = self.model.objects.get(uid=record_id)
        except self.model.DoesNotExist:
            raise ValueError("记录不存在")
        record_ser = self.serializer(instance=record, data=kwargs)
        if record_ser.is_valid():
            return record_ser.save()
        else:
            raise ValueError(str(record_ser.errors))

    def delete_record(self, record_id):
        try:
            record = self.model.objects.get(uid=record_id)
        except self.model.DoesNotExist:
            raise ValueError("记录不存在")
        info = {
            "uid": record_id,
            "is_delete": 1
        }
        record_ser = self.serializer(instance=record, data=info)
        if record_ser.is_valid():
            record_ser.save()
        else:
            raise ValueError(str(record_ser.errors))

    def filter_record(self, **kwargs):
        """
        查询记录
        """
        records = self.model.objects.filter(**kwargs).order_by("-create_time")
        record_ser = self.serializer(instance=records, many=True)
        return record_ser.data

    def filter_record_create_time(self, **kwargs):
        """
        查询记录
        """
        records = self.model.objects.filter(**kwargs).order_by("create_time")
        record_ser = self.serializer(instance=records, many=True)
        return record_ser.data

    def filter_record_no_order(self, **kwargs):
        """
        查询记录 不排序
        """
        records = self.model.objects.filter(**kwargs)
        record_ser = self.serializer(instance=records, many=True)
        return record_ser.data

    def filter_record_order_by_filds(self, *args, **kwargs):
        """
        查询记录 根据某字段排序
        """
        records = self.model.objects.filter(**kwargs)
        for fild_name in args:
            records = records.order_by(fild_name)
        record_ser = self.serializer(instance=records, many=True)
        return record_ser.data
        # fild_name = kwargs.get("fild_name")

    def filter_record_obj(self, **kwargs):
        """
        查询记录
        """
        return self.model.objects.filter(**kwargs).order_by("-create_time")

    def record_serializer(self, records):
        """
        返回序列化结果
        """
        return self.serializer(instance=records, many=True).data

    def record_obj_serializer(self, record):
        """
        序列化单条
        """
        return self.serializer(instance=record).data

    def filter_record_page(self, page, size, **kwargs):
        """
        分页查询记录
        """
        records = self.model.objects.filter(**kwargs).order_by("-create_time")
        paginator = Paginator(records, size)
        record_ser = self.serializer(instance=paginator.page(page).object_list, many=True)
        return (paginator.count, record_ser.data)

    def filter_record_page_conditions(self, *args, **kwargs):
        """
        多条件分页查询
        """
        page = kwargs.get("page")
        size = kwargs.get("size")
        if page is None:
            raise ValueError("page is None")
        if size is None:
            raise ValueError("size is None")
        print(args)
        print(kwargs)
